/*
 * @Author: Await
 * @Date: 2025-05-09 10:45:00
 * @LastEditors: Await
 * @LastEditTime: 2025-05-08 09:33:21
 * @Description: 图表错误处理组件
 */

import React, { Component, ErrorInfo, ReactNode } from 'react';
import { ErrorBoundaryProps, ErrorBoundaryState } from './types';

/**
 * 图表错误边界组件
 * 捕获图表渲染过程中的错误并提供降级UI
 */
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
    constructor(props: ErrorBoundaryProps) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error: Error): ErrorBoundaryState {
        // 更新状态，使下次渲染显示降级UI
        return { hasError: true, error };
    }

    componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
        // 记录错误信息
        console.error('图表渲染错误:', error);
        console.error('错误详情:', errorInfo);

        // 调用错误回调
        this.props.onError?.(error, errorInfo);
    }

    render(): ReactNode {
        if (this.state.hasError) {
            // 自定义降级UI
            return this.props.fallback || (
                <div style={{
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#f0f0f0',
                    color: '#ff4d4f',
                    padding: '20px',
                    boxSizing: 'border-box',
                    textAlign: 'center',
                    zIndex: 10
                }}>
                    <div style={{ marginBottom: '10px', fontSize: '16px' }}>
                        图表渲染失败
                    </div>
                    <div style={{ fontSize: '14px', color: '#666' }}>
                        请检查数据格式或刷新页面重试
                    </div>
                    {this.state.error && (
                        <div style={{
                            marginTop: '20px',
                            padding: '10px',
                            backgroundColor: 'rgba(0,0,0,0.05)',
                            borderRadius: '4px',
                            fontSize: '12px',
                            color: '#999',
                            maxWidth: '100%',
                            overflow: 'auto',
                            textAlign: 'left'
                        }}>
                            {this.state.error.message}
                        </div>
                    )}
                </div>
            );
        }

        return this.props.children;
    }
}

export default ErrorBoundary; 